package FileMangerClient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.JFrame;

import Controllers.Context;
import Controllers.RootController;
import DiskManager.Disk;
import DiskManager.DiskBit;
import FileManager.SimulateContent;
import FileManager.SimulationDirectory;
import FileManager.SimulationFile;
import Tools.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;

/// Attribute D 鏂囦欢澶� T 鏂囨湰鏂囦欢 E 鍙墽琛屾枃浠�
public class MyComputerController extends RootController{
	Disk disk = new Disk();
	String s ="纭洏浼犲叆鍓�";
	
	TreeItem<String> rootItem = new TreeItem<> ("MyCMT");
	public ArrayList<SimulationDirectory> simulationDirectorys = new ArrayList<>();
	public TreeItem<String> selectedItem = new TreeItem<String>();
	AddSomething addsome = new AddSomething();
	SimulationDirectory Current_folder = new SimulationDirectory("MyCMT"," ","D",1,null,disk);
	SimulationDirectory Folder_C = new SimulationDirectory("C"," ","D",2,Current_folder,disk);
	SimulationDirectory Folder_D = new SimulationDirectory("D"," ","D",2,Current_folder,disk);
	SimulationDirectory Folder_E = new SimulationDirectory("E"," ","D",2,Current_folder,disk);
	SimulationDirectory Folder_F = new SimulationDirectory("F"," ","D",2,Current_folder,disk);
	SimulationDirectory MyComputer =Current_folder;
	Stage DiskUsestage = new Stage();
	public VBox Current_VBOX = new VBox();
	public HBox Current_HBOX = new HBox();
	int CopyNum =1;
	public boolean select = false;     //鏄惁閫夋嫨鏂囦欢
	  Parent DiskUseROOT;

	public boolean selectType = false;    //褰撳墠闆腑鐨勬槸鏂囦欢杩樻槸鏂囦欢澶�   false鏂囦欢澶�  true鏂囦欢
	public SimulationDirectory Current_Diretory = Folder_C;
	public SimulationFile      Current_File = new SimulationFile();
    @FXML
    private Button search;
    @FXML
    private  FlowPane FileMenuPane;
    @FXML
    private ScrollPane scrollpane;
    @FXML
    private TextField SearchFile;
    @FXML
    public TextArea result;
    @FXML
    private MenuItem copy;
    @FXML
    private TreeView<String> treeview;
    @FXML
    private MenuItem DiskUse;
    @FXML
    public TextField path;
    @FXML
    private MenuItem DeleteItem;
    @FXML
    private MenuItem CreateItem;
    @FXML
    private MenuItem Edit;
    private void setTreeViewSelectedEvent(TreeView<String> t){
        treeview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {
            @Override
            public void changed(ObservableValue<? extends TreeItem<String>> observable, TreeItem<String> oldValue, TreeItem<String> newValue) {
                selectedItem = newValue;
                for(SimulationDirectory simulationDirectory:simulationDirectorys)
                {
                	if(simulationDirectory.getName().equals(selectedItem.getValue())) {
                		update(simulationDirectory);
                		path.setText(simulationDirectory.getAbsolute());
                		Current_folder = simulationDirectory;
                	
                	}
                }
            }
        });//璁剧疆鐐瑰嚮鏂囦欢澶规爲鐨勬煇涓枃浠跺す鐨勬椂鍊欐洿鏂拌鑺傜偣鐨勫瓙鑺傜偣
           //骞跺湪鏇存柊鍙宠竟鏄剧ず缂╃暐鍥惧強鏂囦欢澶�
           //骞跺湪鏇存柊璺緞鏂囨湰妗�
    }
    
    public MyComputerController() {
    	 Context.controllers.put(this.getClass().getSimpleName(), this);
    }

        public void initialize() throws IOException {
     	this.DiskUseROOT = FXMLLoader.load(getClass().getResource("/FileMangerClient/DiskUsageUI.fxml"));
     	
 	   
	    Scene scene = new Scene(this.DiskUseROOT, 900, 930);
        this.DiskUsestage.initStyle(StageStyle.DECORATED);
        this.DiskUsestage.setScene(scene);
       
       setTreeViewSelectedEvent(treeview);
       Current_folder.setTreeItem(rootItem);
       Current_folder.addChildren(Folder_C, Folder_C.getTreeItem());
       Current_folder.addChildren(Folder_D, Folder_C.getTreeItem());
       Current_folder.addChildren(Folder_E, Folder_C.getTreeItem());
       Current_folder.addChildren(Folder_F, Folder_C.getTreeItem());
       
       addsome.CreateVBox("/FileMangerClient/ddd.png",Folder_C,this);
       Folder_C.setTreeItem(new TreeItem<>(Folder_C.getName()));
       addsome.AddTreeItem(Folder_C, Current_folder,FileMenuPane);
       
       addsome.CreateVBox("/FileMangerClient/ddd.png",Folder_D,this);
       Folder_D.setTreeItem(new TreeItem<>(Folder_D.getName()));
       addsome.AddTreeItem(Folder_D, Current_folder,FileMenuPane);
       
       addsome.CreateVBox("/FileMangerClient/ddd.png",Folder_E,this);
       Folder_E.setTreeItem(new TreeItem<>(Folder_E.getName()));
       addsome.AddTreeItem(Folder_E, Current_folder,FileMenuPane);
       
       addsome.CreateVBox("/FileMangerClient/ddd.png",Folder_F,this); 
       Folder_F.setTreeItem(new TreeItem<>(Folder_F.getName()));
       addsome.AddTreeItem(Folder_F, Current_folder,FileMenuPane);
      
       simulationDirectorys.add(Current_folder);
       simulationDirectorys.add(Folder_C);
       simulationDirectorys.add(Folder_D);
       simulationDirectorys.add(Folder_E);
       simulationDirectorys.add(Folder_F);
       Current_VBOX=Folder_C.getvBox();
       rootItem.setExpanded(true);
       treeview.setRoot(rootItem);
 

    }

    @FXML
    void Search(ActionEvent event) {
    	setSelect(false);
    	FileMenuPane.getChildren().clear();
    	MyComputer.Search(SearchFile.getText(), this);
    }
   
    @FXML
    void CreateItem(ActionEvent event) throws IOException {
    	setSelect(false);
    
    	    CreateFileController controller = new CreateFileController(FileMenuPane);
         	Stage stage = new Stage();
        	Parent root = FXMLLoader.load(getClass().getResource("/FileMangerClient/CreateFile.fxml"));
            Scene scene = new Scene(root, 260, 200);
            stage.initStyle(StageStyle.DECORATED);
            stage.setScene(scene);
            stage.show();
            CreateFileController createFileController = (CreateFileController)Context.controllers.get(CreateFileController.class.getSimpleName());
            createFileController.setDisk(this.disk);
            createFileController.setStage(stage);
    }

    @FXML
    void DeleteItem(ActionEvent event) {
    	
    	if(isSelect())
    	{
    		if(!this.Current_folder.getName().equals("MyCMT")) {
          if(selectType)
          {
        	  FileMenuPane.getChildren().remove(Current_File.getvBox());
        	 if(Current_File.getFather().deleteChild(Current_File,this.disk))
        		 result.setText("鍒犻櫎鎴愬姛");
        	 else
        		 result.setText("鍒犻櫎澶辫触");
          }
          else
          {
              if(Current_Diretory.getChildren().isEmpty())
              {
            	  FileMenuPane.getChildren().remove(Current_Diretory.getvBox());
            	  
            	  if(Current_Diretory.getFather().deleteChild(Current_Diretory,this.disk)&&Current_Diretory.getFather().getTreeItem().getChildren().remove(Current_Diretory.getTreeItem()))
             		 result.setText("鍒犻櫎鎴愬姛");
             	 else
             		 result.setText("鍒犻櫎澶辫触");
              }
              else
              {
            	  result.setText("鍒犻櫎澶辫触:鏂囦欢澶归潪绌�");
              }
          }
    		}
    		else
    		{
    			result.setText("鍒犻櫎澶辫触:涓嶈兘瀵规牴鐩綍杩涜鍒犻櫎鎿嶄綔");
    		}
    	}
    	else
    		result.setText("鍒犻櫎澶辫触:娌℃湁閫夋嫨鏂囦欢");
    } 
   
	public void update(SimulationDirectory simulationDirectory) {
		setSelect(false);
    	 System.out.println(simulationDirectory.getAttribute());
         FileMenuPane.getChildren().clear();
         Current_folder = simulationDirectory;
         for(SimulateContent simulateContents :simulationDirectory.getChildren())
         {
        	
        	 if(simulateContents.getAttribute().equals("D"))
        	addsome.CreateVBox("/FileMangerClient/ddd.png",(SimulationDirectory)simulateContents, this);
        	 else
        	addsome.CreateVBox("/FileMangerClient/File.png",(SimulationFile)simulateContents, this);
        		 
         }
    }
    @FXML
    void copy(ActionEvent event) {  //澶嶅埗绮樿创

    	if(isSelect())
    	{
    	if(!this.Current_folder.getName().equals("MyCMT")) {
        	if(copy.getText().equals("澶嶅埗"))
        	copy.setText("榛忚创");
        	else
        	{
        	if(selectType)
            {
          	 SimulationFile copyFile = new SimulationFile(Current_File.getName()+Integer.toString(CopyNum++), Current_File.getExtendName(), 
         	 Current_File.getAttribute(), this.creatNewFile(Current_folder, disk), Current_folder, Current_File.getSize(),disk);
          	if(Current_folder.getStartnum()!=1)Current_folder.saveContentArrary(disk);
          	copyFile.setContent(Current_File.getContent());
          	copyFile.saveContentArrary(disk);
          	 addsome.CreateVBox("/FileMangerClient/File.png",copyFile,this);
          	 copy.setText("澶嶅埗");
          	 setSelect(false);
            }
            else
            {
            	
               if(Current_Diretory.getChildren().isEmpty())
                {
              	  SimulationDirectory copyEmptyD = new SimulationDirectory(Current_Diretory.getName()+Integer.toString(CopyNum++),
              			  Current_Diretory.getExtendName(), Current_Diretory.getAttribute(), this.creatNewFile(Current_folder, disk), Current_folder,disk);
              	if(Current_folder.getStartnum()!=1)Current_folder.saveContentArrary(disk);
              	copyEmptyD.saveContentArrary(disk);
              	addsome.CreateVBox("/FileMangerClient/ddd.png",copyEmptyD,this);
 			   addsome.AddTreeItem(copyEmptyD,this.Current_folder,this.getFlowPane());
 		       simulationDirectorys.add(copyEmptyD);
 		      copy.setText("澶嶅埗");
           	 setSelect(false);
                }
                else
                {
                	copyNotEmptyD(this.Current_Diretory,this.Current_folder);
                	copy.setText("澶嶅埗");
                }
            	
            }
        	}
    	}
    	else
    	{
    		result.setText("澶嶅埗澶辫触:涓嶈兘瀵规牴鐩綍杩涜澶嶅埗鎿嶄綔");
    	}
    	}
    	else {
    		result.setText("澶嶅埗澶辫触:娌℃湁閫夋嫨鏂囦欢");
    	}
    }
    
    @FXML
    void Editting(ActionEvent event) {
    	if(!Current_File.getName().equals("")) {
    	 JFrame wordwin=new Wordwin(Current_File,this.disk);   
         wordwin.setVisible(true);
         }
    	else
    	{
    		result.setText("娌￠�変腑鐩稿簲鏂囦欢杩涜缂栬緫");
    	}
    }
    
    public void copyNotEmptyD(SimulationDirectory copyD,SimulationDirectory father) {
    	SimulationDirectory newD ;
    	if(father.isHaveName(copyD.getName())) {
    	newD = new SimulationDirectory(copyD.getName()+Integer.toString(CopyNum++), copyD.getExtendName(), 
        			copyD.getAttribute(), this.creatNewFile(father, disk), father,disk);
    	newD.setSize(copyD.getSize());
    	}
    	else {
    	newD = new SimulationDirectory(copyD.getName(), copyD.getExtendName(), 
    			copyD.getAttribute(), this.creatNewFile(father, disk), father,disk);
    	newD.setSize(copyD.getSize());
    	}
    	
    	   newD.setTreeItem(new TreeItem<>(newD.getName()));
    	   if(father.getStartnum()!=1)father.saveContentArrary(disk);
		   newD.saveContentArrary(disk);
		   if(father.equals(this.Current_folder))
    	   addsome.CreateVBox("/FileMangerClient/ddd.png",newD,this);
		   addsome.AddTreeItem(newD,this.Current_folder,this.getFlowPane());
	       simulationDirectorys.add(newD);
    	for(SimulateContent content:copyD.getChildren()) {
    		if(content.getAttribute().equals("D"))
    		{
    	       copyNotEmptyD((SimulationDirectory)content,newD);
    		}
    		else
    		{   
    			SimulationFile  ccFile = (SimulationFile)content;
    			SimulationFile newF = new SimulationFile(content.getName(), content.getExtendName(), content.getAttribute(), this.creatNewFile(newD, disk), newD, ccFile.getSize(),disk);  
    			newF.setContent(ccFile.getContent());
    			if(newD.getStartnum()!=1)newD.saveContentArrary(disk);
    			newF.saveContentArrary(disk);
    		}
    	}
    }
    
    @FXML
    void DiskUse(ActionEvent event) {
    	 DiskUsageUIController diskUsageUIController = (DiskUsageUIController)Context.controllers.get(DiskUsageUIController.class.getSimpleName());
 	    diskUsageUIController.update(disk);
 	   this.DiskUsestage.show();
    }
    
    
    public int creatNewFile(SimulationDirectory dir,Disk disk) {
		int fatherStartNum = dir.getStartnum();
		char directory = judgeDirectory(dir,fatherStartNum);
		int startnum = creatStartNum(directory,disk);
		if(startnum==-1) {
			System.out.println("not enough space");
		}
		return startnum;
	}
	
	char judgeDirectory(SimulationDirectory dir,int startnum) {
		if(startnum==2) {
			switch(dir.getName()) {
			case("C"):return 'C';
			case("D"):return 'D';
			case("E"):return 'E';
			case("F"):return 'F';
			}
		}
		if(startnum>=3&&startnum<=62)return 'C';
		if(startnum>=63&&startnum<=122)return 'D';
		if(startnum>=123&&startnum<=182)return 'E';
		if(startnum>=183&&startnum<=242)return 'F';
		System.out.println("judgeDirectory_ERROR");
		return 'N';
	}
	
	private int creatStartNum(char directory,Disk disk) {
		int start = 4; 
		int end = 62;
		switch(directory){
		case('C'):break;
		case('D'):start += 60;end += 60;break;
		case('E'):start +=120;end += 120;break;
		case('F'):start +=180;end += 180;break;
		case('N'):return 243;
		}
		int[] fat = disk.getFAT();
		for (int i=start;i<=end;i++) {
			if(fat[i]==0) {
				fat[i]=-1;
				return i;
			}
		}
		return -1;
	}
    
    
    //getter and setter
    public SimulationDirectory getCurrent_folder() {
		return Current_folder;
	}

	public void setCurrent_folder(SimulationDirectory current_folder) {
		Current_folder = current_folder;
	}

	public boolean isSelectType() {
		return selectType;
	}

	public VBox getCurrent_VBOX() {
		return Current_VBOX;
	}

	public void setCurrent_VBOX(VBox current_VBOX) {
		Current_VBOX = current_VBOX;
	}
	public HBox getCurrent_HBOX() {
		return Current_HBOX;
	}

	public void setCurrent_HBOX(HBox current_HBOX) {
		Current_HBOX = current_HBOX;
	}


	public void setSelectType(boolean selectType) {
		this.selectType = selectType;
	}

	public SimulationDirectory getCurrent_Diretory() {
		return Current_Diretory;
	}

	public void setCurrent_Diretory(SimulationDirectory current_Diretory) {
		Current_Diretory = current_Diretory;
	}

	public SimulationFile getCurrent_File() {
		return Current_File;
	}

	public void setCurrent_File(SimulationFile current_File) {
		Current_File = current_File;
	}
	public boolean isSelect() {
		return select;
	}

	public void setSelect(boolean select) {
		this.select = select;
	}
	 public FlowPane getFlowPane()
	    {
	    	return this.FileMenuPane;
	    }
	 
	 public final Disk getDisk() {
			return disk;
		}

		public final void setDisk(Disk disk) {
			this.disk = disk;
		}

		public final String getS() {
			return s;
		}

		public final void setS(String s) {
			this.s = s;
		}

		public final TreeItem<String> getSelectedItem() {
			return selectedItem;
		}

		public final void setSelectedItem(TreeItem<String> selectedItem) {
			this.selectedItem = selectedItem;
		}
	 
	 
}
